const express = require("express");
const route = express.Router();
const adminModel = require("../db/model/adminModel")
const md5 = require("md5")
const {
  jwtEncode
} = require("../utils/jwt")

route.post("/login", async (req, res) => {
  const {
    adminName,
    password
  } = req.body;
  // console.log(adminName, password);

  //首先检验是否登录成功
  try {
    const findResult = await adminModel.findOne({
      adminName,
      password: md5(password + "123")
    })

    //查询不到的情况
    if (!findResult) {
      return res.send({
        code: 10002,
        msg: "登录异常:账号或者密码错误",
        data: null
      })
    }

    //查询到了以后,根据我们封装的jwt规范,生成一个token 响应给用户
    // console.log(findResult);
    const token = jwtEncode(findResult.adminName, "666");
    // console.log(token);
    // 登录成功后把当前的用户状态改为1
    await adminModel.updateOne({
      adminName
    },{
      $set:{
        status:1
      }
    })
    res.send({
      code: 10000,
      msg: "登录成功",
      data: {
        token
      }
    })
  } catch (e) {
    console.log("登录查询时发生异常", e.message);
    res.send({
      code: 10001,
      msg: "登录查询时发生异常:" + e.message,
      data: null
    })
  }


})

module.exports = route;